package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
)

type INoticeRepository interface {
	FindById(db *gorm.DB, id uint) (*model.Notice, error)
	Crate(db *gorm.DB, notice *model.Notice) error
	Updates(db *gorm.DB, notice *model.Notice) error
	DeleteBatch(db *gorm.DB, ids []uint) error
	FindPage(db *gorm.DB, params *pagehelper.Params) ([]*model.Notice, error)
	Count(db *gorm.DB, params *pagehelper.Params) (int64, error)
	FindTopList(db *gorm.DB) ([]*model.Notice, error)
}

type NoticeRepository struct {
}

func NewNoticeRepository() INoticeRepository {
	return &NoticeRepository{}
}

func (r *NoticeRepository) FindById(db *gorm.DB, id uint) (notice *model.Notice, err error) {
	return notice, db.First(&notice, id).Error
}

func (r *NoticeRepository) FindPage(db *gorm.DB, params *pagehelper.Params) (page []*model.Notice, err error) {
	tx := db.Model(&model.Notice{}).Where(params.WherePair.Query, params.WherePair.Args...)
	return page, tx.Scopes(pagehelper.Paginate(params.Current, params.Size)).Find(&page).Error
}

func (r *NoticeRepository) Count(db *gorm.DB, params *pagehelper.Params) (count int64, err error) {
	tx := queryWrapper.ReuseSelect(db.Model(&model.Notice{}), params.SelectFields)
	return count, queryWrapper.ReuseWherePair(tx, params.WherePair).Count(&count).Error
}

func (r *NoticeRepository) Crate(db *gorm.DB, notice *model.Notice) error {
	return db.Create(&notice).Error
}

func (r *NoticeRepository) Updates(db *gorm.DB, notice *model.Notice) error {
	return db.Model(&model.Notice{}).Where("id = ?", notice.Id).Updates(&notice).Error
}

func (r *NoticeRepository) DeleteBatch(db *gorm.DB, ids []uint) error {
	return db.Delete(&model.Notice{}, ids).Error
}

func (r *NoticeRepository) FindTopList(db *gorm.DB) (list []*model.Notice, err error) {
	return list, db.Model(&model.Notice{}).Where("status = 2 and is_top = 2").Order("created_at desc").Find(&list).Error
}
